//
//  EditOwnerInfoForIndividualView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/6/1.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import RxGesture
class EditOwnerInfoForIndividualView: View {
    private lazy var disposeBag = DisposeBag()
    @objc dynamic var viewModel: EditOwnerInfomationViewModel!
    //View
    let firstNameView = TextFieldWithRequiredView(.username)
    let surenameView = TextFieldWithRequiredView(.username)
    let mobileView = TextFieldWithRequiredView(.phone)
    let emailView = TextFieldWithRequiredView(.email)
    let gstSwitchBtn = SwitchButton()
    let coOwnerFirstNameView = TextFieldWithRequiredView(.username)
    let coOwnerSurenameView = TextFieldWithRequiredView(.username)
    let coOwnerRelationshipView = TextFieldWithRequiredView()
    let coOwnerOptionLabel = ContentLabel()
    let coOwnerOptionSwitchBtn = SwitchButton()
    lazy var coOwnerBackView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        return view
    }()
    override func setUpView() {
        //1.first name title
        let firstNameTitle = LabelWithRedStarView(R.string.localizable.firstName())
        self.addSubview(firstNameTitle)
        firstNameTitle.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //1.1.first name textfield\
        self.addSubview(firstNameView)
        firstNameView.snp.makeConstraints { (make) in
            make.top.equalTo(firstNameTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(firstNameTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //2.1.first name textfield
        self.addSubview(surenameView)
        surenameView.snp.makeConstraints { (make) in
            make.top.equalTo(firstNameView)
            make.left.equalTo(firstNameView.snp.right).offset(Constant.InternalMargin)
            make.right.equalToSuperview()
            make.width.equalTo(firstNameView)
            make.height.greaterThanOrEqualTo(0)
        }
        //2.last name title
        let surenameTitle = LabelWithRedStarView(R.string.localizable.surname())
        self.addSubview(surenameTitle)
        surenameTitle.snp.makeConstraints { (make) in
            make.top.equalTo(firstNameTitle)
            make.left.equalTo(surenameView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.mobile
        let mobileTitle = LabelWithRedStarView(R.string.localizable.mobile())
        self.addSubview(mobileTitle)
        mobileTitle.snp.makeConstraints { (make) in
            make.top.equalTo(firstNameView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(firstNameTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.1.mobile textfield
        self.addSubview(mobileView)
        mobileView.snp.makeConstraints { (make) in
            make.top.equalTo(mobileTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //4.Email
        let emailTitle = LabelWithRedStarView(R.string.localizable.email())
        self.addSubview(emailTitle)
        emailTitle.snp.makeConstraints { (make) in
            make.top.equalTo(mobileView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(firstNameTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.1.Email textfield
        self.addSubview(emailView)
        emailView.snp.makeConstraints { (make) in
            make.top.equalTo(emailTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(mobileView)
            make.height.greaterThanOrEqualTo(0)
        }
        //gst
        self.addSubview(gstSwitchBtn)
        gstSwitchBtn.snp.makeConstraints { (make) in
            make.top.equalTo(emailView.snp.bottom).offset(Constant.SectionTopMargin)
            make.right.equalTo(mobileView)
            make.size.equalTo(SwitchButton.size)
        }
        let gstTitle = ContentLabel(text: R.string.localizable.gsT())
        self.addSubview(gstTitle)
        gstTitle.snp.makeConstraints { (make) in
            make.centerY.equalTo(gstSwitchBtn)
            make.left.equalTo(firstNameTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.co owner
        self.addSubview(coOwnerOptionSwitchBtn)
        coOwnerOptionSwitchBtn.snp.makeConstraints { (make) in
            make.top.equalTo(gstSwitchBtn.snp.bottom).offset(Constant.SectionTopMargin)
            make.right.equalTo(gstSwitchBtn)
            make.size.equalTo(SwitchButton.size)
        }
        //
        var font = R.font.interRegular(size: 15)!
        if Constant.standardViewFlag == false{
            font = font.withSize(font.pointSize * Constant.magnifiedViewScale)
        }
        let firstStr = "Co-Owner"
        let secStr = "(Optional)"
        let attrString = NSMutableAttributedString(string: firstStr + secStr)
        let strSubAttr1: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#292D32"),.font: font]
        let strSubAttr2: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#292D3266"),.font: font]
        attrString.addAttributes(strSubAttr1, range: NSRange(location: 0, length: firstStr.count))
        attrString.addAttributes(strSubAttr2, range: NSRange(location: firstStr.count, length: secStr.count))
        coOwnerOptionLabel.attributedText = attrString
        self.addSubview(coOwnerOptionLabel)
        coOwnerOptionLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(coOwnerOptionSwitchBtn)
            make.left.equalTo(firstNameTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.1.
        self.addSubview(coOwnerBackView)
        coOwnerBackView.snp.makeConstraints { (make) in
            make.top.equalTo(coOwnerOptionSwitchBtn.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.right.equalTo(mobileView)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //1.first name title
        let coOwnerFirstNameTitle = LabelWithRedStarView(R.string.localizable.firstName())
        coOwnerBackView.addSubview(coOwnerFirstNameTitle)
        coOwnerFirstNameTitle.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //1.1.first name textfield
        coOwnerBackView.addSubview(coOwnerFirstNameView)
        coOwnerFirstNameView.snp.makeConstraints { (make) in
            make.top.equalTo(coOwnerFirstNameTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //2.last name title
        //2.1.first name textfield
        coOwnerBackView.addSubview(coOwnerSurenameView)
        coOwnerSurenameView.snp.makeConstraints { (make) in
            make.top.equalTo(coOwnerFirstNameView)
            make.left.equalTo(coOwnerFirstNameView.snp.right).offset(Constant.InternalMargin)
            make.right.equalToSuperview()
            make.width.equalTo(coOwnerFirstNameView)
            make.height.greaterThanOrEqualTo(0)
        }
        let coOwnerSurenameTitle = LabelWithRedStarView(R.string.localizable.surname())
        coOwnerBackView.addSubview(coOwnerSurenameTitle)
        coOwnerSurenameTitle.snp.makeConstraints { (make) in
            make.centerY.equalTo(coOwnerFirstNameTitle)
            make.left.equalTo(coOwnerSurenameView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //3.co owner relation shipe
        let coOwnerRelationshipTitle = LabelWithRedStarView(R.string.localizable.relationship())
        coOwnerBackView.addSubview(coOwnerRelationshipTitle)
        coOwnerRelationshipTitle.snp.makeConstraints { (make) in
            make.top.equalTo(coOwnerFirstNameView.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(coOwnerFirstNameTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //2.1.first name textfield
        coOwnerRelationshipView.textField.showRightImageView("installation_list_search_down_arrow")
        coOwnerRelationshipView.textField.placeholder = R.string.localizable.selectRelationship()
        coOwnerRelationshipView.textField.isEnabled = false
        coOwnerRelationshipView.textField.clearButtonMode = .never
        coOwnerBackView.addSubview(coOwnerRelationshipView)
        coOwnerRelationshipView.snp.makeConstraints { (make) in
            make.top.equalTo(coOwnerRelationshipTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-Constant.TopBottomMargin)
        }
        self.initBiding()
    }
    //MARK: - 点击coowner switch
    @objc private func coOwnerOptionSwitchBtnClick(){
        self.viewModel.co_owner_optional = !self.viewModel.co_owner_optional
        self.coOwnerOptionSwitchBtn.switchOn(self.viewModel.co_owner_optional)
        self.dealCoOwnerInfo(showCoOwnerFlag: self.viewModel.co_owner_optional)
        if self.viewModel.co_owner_optional {
            self.coOwnerFirstNameView.textField.becomeFirstResponder()
        }
    }
    //MARK: 处理cowoner info 的显示
    private func dealCoOwnerInfo(showCoOwnerFlag: Bool){
        if showCoOwnerFlag { //co owner有值
            self.coOwnerBackView.isHidden = false
            self.coOwnerOptionSwitchBtn.snp.remakeConstraints { (make) in
                make.top.equalTo(self.gstSwitchBtn.snp.bottom).offset(Constant.SectionTopMargin)
                make.right.equalTo(self.mobileView)
                make.height.width.greaterThanOrEqualTo(0)
            }
            self.coOwnerBackView.snp.remakeConstraints { (make) in
                make.top.equalTo(self.coOwnerOptionSwitchBtn.snp.bottom).offset(Constant.TopBottomMargin)
                make.left.right.equalTo(self.mobileView)
                make.height.greaterThanOrEqualTo(0)
                make.bottom.equalToSuperview()
            }
        }else{//co owner没有值
            self.coOwnerBackView.isHidden = true
            self.coOwnerOptionSwitchBtn.snp.remakeConstraints { (make) in
                make.top.equalTo(self.gstSwitchBtn.snp.bottom).offset(Constant.SectionTopMargin)
                make.right.equalTo(self.mobileView)
                make.height.width.greaterThanOrEqualTo(0)
                make.bottom.equalTo(-Constant.TopBottomMargin)
            }
            self.coOwnerBackView.snp.remakeConstraints { (make) in
                make.left.right.equalTo(self.mobileView)
                make.height.greaterThanOrEqualTo(0)
                make.bottom.equalTo(self.coOwnerOptionLabel)
            }
        }
    }
    private func initBiding(){
        coOwnerOptionSwitchBtn.addTarget(self, action: #selector(coOwnerOptionSwitchBtnClick), for: UIControl.Event.touchUpInside)
        //监听first name内容
        firstNameView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.first_name = data
        }
        //监听sur name内容
        surenameView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.surname = data
        }
        //监听mobile内容
        mobileView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.mobile = data
        }
        //监听email内容
        emailView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.email = data
        }
        //监听coOwnerFirstName内容
        coOwnerFirstNameView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.co_owner_first_name = data
        }
        //监听coOwnerSurName内容
        coOwnerSurenameView.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.co_owner_surname = data
        }
        //选择relation ship
        coOwnerRelationshipView.rx.tapGesture().when(.recognized).subscribe { [weak self] _ in
            guard let strongSelf = self else {return }
            strongSelf.selectRelationShip()
        }.disposed(by: self.disposeBag)
        //切换gst
        gstSwitchBtn.rx.observe(Int.self, "tag").subscribe(onNext: {[weak self] (btnTag) in
            guard let strongSelf = self, let tag = btnTag, let _ = strongSelf.viewModel else {return }
            if tag == 1{//开启pick up required
                strongSelf.viewModel.gst = true
            }else{//关闭
                strongSelf.viewModel.gst = false
            }
            
        }).disposed(by: self.disposeBag)
        //
        
    }
    func setData(_ model: EditOwnerInfomationViewModel){
        self.viewModel = model
        self.gstSwitchBtn.switchOn(self.viewModel.gst)
        self.firstNameView.textField.text = self.viewModel.first_name
        self.surenameView.textField.text = self.viewModel.surname
        self.coOwnerFirstNameView.textField.text =  self.viewModel.co_owner_first_name
        self.coOwnerSurenameView.textField.text = self.viewModel.co_owner_surname
        self.coOwnerRelationshipView.textField.text = self.viewModel.co_owner_relation_ship_name
        self.mobileView.textField.text = self.viewModel.mobile
        self.emailView.textField.text = self.viewModel.email
        self.setCoOwnerInfo(haveCoownerInfoFlag:self.viewModel.showCoOwnerFlag)
    }
    //MARK: -
    private func selectRelationShip(){
        self.endEditing(true)
        let cellList = [CellModel(title: CoOwnerRelationShipName.partner.rawValue, value: CoOwnerRelationShipValue.partner.rawValue),
                        CellModel(title: CoOwnerRelationShipName.familyMenber.rawValue, value: CoOwnerRelationShipValue.familyMenber.rawValue),
                        CellModel(title: CoOwnerRelationShipName.coowner.rawValue, value: CoOwnerRelationShipValue.coowner.rawValue)]
        let actionSheetView = CustomActionSheet(title: R.string.localizable.selectRelationship(), aCellArray: cellList, aCancelModel: CellModel(title: R.string.localizable.cancel()), aSelectedClosure: { [weak self](row) in
            guard let strongSelf = self else {return}
            strongSelf.viewModel.co_owner_relation_ship = cellList[row].value
            strongSelf.coOwnerRelationshipView.textField.text = cellList[row].title
            strongSelf.coOwnerRelationshipView.hideInvalidMsg()
        }, aCancelClosure: nil)
        if let rootView = Tool.getRootView(){
            rootView.addSubview(actionSheetView)
        }
        
    }
    //MARK: - 打开编辑时，检验必填项及有效信息
    func validateAllRequiredFieldWhenEdit(){
        self.emailView.checkIfStandardValid()
        self.mobileView.checkIfStandardValid()
        self.firstNameView.checkIfStandardValid()
        self.surenameView.checkIfStandardValid()
        
        //co owner信息校验
        if self.viewModel.co_owner_optional {
            self.coOwnerFirstNameView.checkIfStandardValid()
            self.coOwnerSurenameView.checkIfStandardValid()
            self.coOwnerRelationshipView.checkIfStandardValid()
        }
    }
    //MARK: - 处理GST的默认值（create job初始化，或改变property type，或改变owner type,或改变ABN）
    func dealGSTValue(gstFlag: Bool){
        guard let _ = self.viewModel else {return}
        self.viewModel.gst = false
        self.gstSwitchBtn.switchOn(self.viewModel.gst)
    }
    private func setCoOwnerInfo(haveCoownerInfoFlag: Bool){
        if haveCoownerInfoFlag {//solar panel有co owner info
            if self.viewModel.co_owner_first_name != "" && self.viewModel.co_owner_surname != ""{
                self.viewModel.co_owner_optional = true
                self.coOwnerOptionSwitchBtn.switchOn(true)
            }else{
                self.viewModel.co_owner_optional = false
                self.coOwnerOptionSwitchBtn.switchOn(false)
            }
        }else{//热水器不显示co owner info
            self.viewModel.co_owner_optional = false
            self.coOwnerOptionSwitchBtn.switchOn(false)
            self.coOwnerOptionLabel.isHidden = true
            self.coOwnerOptionSwitchBtn.isHidden = true
        }
        //
        self.dealCoOwnerInfo(showCoOwnerFlag: self.viewModel.co_owner_optional)
    }
}
